/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.huangjianbo.supos.openapi.core.thread;

/**
 * 客户端上下文持有者（基于线程本地变量的上下文管理）
 * <p>
 * 通过 {@link InheritableThreadLocal} 实现线程安全的上下文存储，支持父子线程间的上下文继承
 * 
 * @author tomcat
 * @version 1.0
 */
public final class ClientContextHolder {
    /**
     * 线程本地上下文存储器
     * <p>
     * 使用可继承的线程本地变量，确保子线程可以继承父线程的上下文配置<br>
     * 默认初始值为 {@link ClientContextImpl} 实例
     */
    private static final ThreadLocal<ClientContext> CLIENT_CONTEXT_THREAD_LOCAL = new InheritableThreadLocal<ClientContext>() {
        @Override
        protected ClientContext initialValue() {
            return new ClientContextImpl();
        }
    };

    /**
     * 获取当前线程的客户端上下文
     * 
     * @return 当前线程关联的上下文对象（永不为null）
     */
    public static ClientContext getContext() {
        return CLIENT_CONTEXT_THREAD_LOCAL.get();
    }

    /**
     * 设置或清除当前线程的客户端上下文
     * 
     * @param context 新的上下文对象（传入null会触发上下文清除）
     */
    public static void setContext(ClientContext context) {
        if (context == null) {
            removeContext();
        } else {
            CLIENT_CONTEXT_THREAD_LOCAL.set(context);
        }
    }

    /**
     * 清除当前线程的客户端上下文
     * <p>
     * 调用后 {@link #getContext()} 将返回新的默认上下文实例
     */
    public static void removeContext() {
        CLIENT_CONTEXT_THREAD_LOCAL.remove();
    }
}
